<div class="layuimini-main" style="padding-left: 40px">

    <div class="layui-form layui-form-pane">
        <fieldset class="layui-elem-field  layui-field-title">
            <legend>新增</legend>
        </fieldset>
        @foreach( $data['model_fields'] as $field)
            @switch($field->form_type)
                @case('input')
                <div class="layui-form-item">
                    <label class="layui-form-label required">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                        <input type="text" class="layui-input"
                               name="{{ $field->name }}"
                               lay-verify="@if($field->is_required == 1){{'required'}}@endif"
                               value="{{ $content->{$field->name} ?? $field->form_default }}">
                    </div>
                </div>
                @break
                @case('textArea')
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label required">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                    <textarea class="layui-textarea"
                              name="{{ $field->name }}"
                              lay-verify="@if($field->is_required == 1){{'required'}}@endif"
                          placeholder="长度不超过200个字符">{{ $content->{$field->name} ?? $field->form_default }}</textarea>
                    </div>
                </div>
                @break
                @case('richText')
                <div class="layui-form-item layui-form-text">
                    <label class="layui-form-label">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                        <textarea cols="30" rows="10"
                                  name="{{ $field->name }}"
                                  id="{{ $field->name }}" >{{ $content->{$field->name} ?? $field->form_default }}</textarea>
                    </div>
                </div>
                <script src="{{ asset('/admin/lib/tinymce/tinymce.min.js') }}"></script>
                <script>
                    tinymce.init({
                        selector:'#{{ $field->name }}',
                        language:'zh_CN',
                        plugins: 'print preview searchreplace autolink directionality visualchars fullscreen image link media template code table charmap hr pagebreak nonbreaking anchor insertdatetime advlist lists wordcount imagetools textpattern paste emoticons  autoresize',
                        toolbar: 'preview code | removeformat alignleft aligncenter alignright indent2em lineheight  | fontsizeselect forecolor backcolor bold italic underline strikethrough link anchor | bullist numlist | blockquote subscript superscript | table image media charmap hr pagebreak insertdatetime | fullscreen ',
                        fontsize_formats: '12px 14px 16px 18px 24px 36px 48px 56px 72px',
                        autosave_ask_before_unload: false,
                        toolbar_drawer : false,
                        // 图片上传
                        images_upload_handler: function (blobInfo, success, failure) {
                            var xhr, formData;
                            xhr = new XMLHttpRequest();
                            xhr.withCredentials = false;
                            xhr.open('POST', '{{route("image.editor")}}');
                            var token = '{{ csrf_token() }}';
                            xhr.setRequestHeader("X-CSRF-Token", token);
                            xhr.onload = function() {
                                var json;
                                if (xhr.status != 200) {
                                    failure('HTTP Error: ' + xhr.status);
                                    return;
                                }
                                json = JSON.parse(xhr.responseText);

                                if (!json || typeof json.location != 'string') {
                                    failure('Invalid JSON: ' + xhr.responseText);
                                    return;
                                }
                                success(json.location);
                            };
                            formData = new FormData();
                            formData.append('file', blobInfo.blob(), blobInfo.filename());
                            xhr.send(formData);
                        },
                        setup: function(editor){
                            editor.on('change',function(){ editor.save(); });
                        },
                    })
                </script>
                @break
                @case('upload')
                <div class="layui-form-item">
                    <label class="layui-form-label">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="{{$field->name}}">上传图片</button>
                            <input type="text" disabled="disabled"
                                   name="{{ $field->name }}"
                                   value="{{ $content->{$field->name} ?? $field->form_default }}"
                                   lay-verify="@if($field->is_required == 1){{'required'}}@endif"
                                   style="float: left; width: 50%;" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-upload-list" >
                        <img class="layui-upload-img" id="upload-preview-{{$field->name}}"
                             src="{{ $content->{$field->name} ?? $field->form_default }}" style="border: 1px solid #cccccc;width: 300px;">
                        <p id="demo_text"></p>
                    </div>
                    <script>
                        layui.use(['miniUpload'],function (){
                            var miniUpload = layui.miniUpload
                            miniUpload.uploadImg('{{$field->name}}', 'upload-preview-{{$field->name}}');
                        })
                    </script>
                </div>
                @break
                @case('uploadMulti')
                <div class="layui-form-item">
                    <label class="layui-form-label">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="{{ $field->name }}">多图片上传</button>
                            <input type="text" disabled="disabled" style="float:left; width: 50%;" autocomplete="off" class="layui-input"
                                   name="{{ $field->name }}"
                                   lay-verify="@if($field->is_required == 1){{'required'}}@endif"
                                   value="{{ $content->{$field->name} ?? $field->form_default }}" >
                        </div>
                    </div>
                    <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                        预览图：
                        <div class="layui-upload-list" id="upload-preview-{{$field->name}}">
                            @if(isset($content))
                                @foreach( explode(',', $content->{$field->name}) as $v )
                                    <span style="position: relative;width: 200px;height: 200px" class="imgs">
                            <img style="width: 200px;" src="{{ $v }}" alt="" class="layui-upload-img">
                            <i class="layui-icon" title="移除图片" style="color: #ff0000;font-size: 60px; position: absolute;top:0 ; right: 40%;cursor: pointer;  "></i>
                            </span>
                                @endforeach
                            @endif
                        </div>
                    </blockquote>
                    <script>
                        layui.use(['miniUpload'],function (){
                            var miniUpload = layui.miniUpload
                            miniUpload.uploadImages('{{$field->name}}', 'upload-preview-{{$field->name}}');
                        })
                    </script>
                </div>
                @break
                @case('uploadFile')
                <div class="layui-form-item">
                    <label class="layui-form-label">{{ $field->form_name }}</label>
                    <div class="layui-input-block">
                        <div class="layui-upload">
                            <button type="button" class="layui-btn" id="{{$field->name}}">上传文件</button>
                            <input type="text" disabled="disabled"
                                   name="{{ $field->name }}"
                                   value="{{ $content->{$field->name} ?? $field->form_default }}"
                                   lay-verify="@if($field->is_required == 1){{'required'}}@endif"
                                   style="float: left; width: 50%;" autocomplete="off" class="layui-input">
                        </div>
                    </div>
                    <div class="layui-upload-list" >
                        <p id="demo_text"></p>
                    </div>
                    <script>
                        layui.use(['miniUpload'],function (){
                            var miniUpload = layui.miniUpload
                            miniUpload.uploadFile('{{$field->name}}', 'upload-preview-{{$field->name}}');
                        })
                    </script>
                </div>
                @break
            @endswitch
        @endforeach
        <div class="layui-form-item">
            <div class="layui-input-block">
                <input type="checkbox" id="form_type" name="" title="修改"
                       value="@if(isset($content)){{1}}@endif"
                       @if(isset($content)) checked @endif
                       lay-skin="primary" disabled>
                <input type="hidden" value="@if(isset($content)){{ $content->id }}@endif" id="id" name="id">
                <input type="hidden" value="{{ $data['type'] }}" id="type" name="type">
                <button class="layui-btn layui-btn-normal" lay-submit lay-filter="saveBtn">确认保存</button>
            </div>
        </div>
        <div class="layui-form-item"></div>
    </div>
</div>

<script>
    layui.use(['form', 'iconPickerFa','miniUpload'], function () {
        var form = layui.form,
            layer = layui.layer,
            $ = layui.$;
        var miniPage = layui.miniPage;

        /**
         * 初始化表单，要加上，不然刷新部分组件可能会不加载
         */
        form.render();

        //监听提交
        form.on('submit(saveBtn)', function (data) {
            console.log($('#form_type').val() == 0)
            var url = '';
            var method = '';
            var type = $('#type').val();
            if ($('#form_type').val() == 0){
                url = 'content/'+ type;
                method = 'POST'
            }else {
                url =  'content/'+ type+'/'+ data.field.id;
                method = 'PUT'
            }
            console.log(data.field)

            $.ajax({
                url: url,
                method: method,
                data: data.field,
                success: function (res) {
                    console.log(res)
                    if (res.code === 0) {
                        layer.msg('保存成功', {icon: 1}, function () {
                            // 刷新列表
                            var options = {};
                            options.homeInfo = options.homeInfo || {};
                            miniPage.refresh(options);
                        })
                    } else {
                        layer.msg(res.msg, {icon: 5})
                    }
                },
                error: function (res) {
                    layer.msg(res+',请全部填写', {icon: 5})
                }
            });
            return false;
        });
    });
</script>

